package research.ui.editors.tableeditors.formula;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.swt.widgets.Composite;

import research.domain.Component;
import research.domain.ComponentValue;
import research.entity.Entity;
import research.entity.EntityType;
import research.ui.editors.tableeditors.EntityTableEditor;

public class FormulaTableEditor extends EntityTableEditor {

	private List<Entity> components;

	public FormulaTableEditor(Composite parent, List<Entity> components) {
		super(EntityType.ComponentValue);
		this.components = components;

		render(parent);
		
		setCellModifier(new FormulaCellModifier(this));
		setLabelProvider(new FormulaLabelProvider());
		setSorter(new FormulaSorter());
	}

	@Override
	protected List<ColumnData> getColumnsData() {

		List<ColumnData> columns = new ArrayList<ColumnData>();
		columns.add(new ColumnData("Компонент", 120, createComboBoxCellEditor(getComponentsNames())));
		columns.add(new ColumnData("Доля, %", 60, createTextCellEditor(10)));
		columns.add(new ColumnData("Основной", 80, createCheckBoxCellEditor()));
		

		return columns;
	}

	public String[] getComponentsNames() {
		List<String> res = new ArrayList<String>();
		for (Entity component : components) {
			res.add(((Component) component).getName());
		}
		return res.toArray(new String[] {});
	}
	
	public Component getComponentByNameIdx(int idx) {
		String[] names = getComponentsNames();
		if (idx < 0 || idx > names.length || names.length == 0)
			return null;
		
		String name = names[idx];
		for (Entity component : components) {
			Component comp = (Component) component;
			if (comp.getName().equals(name))
				return comp;
		}
		return null;
	}
	
	public void setMain(ComponentValue value) {
		for (Entity entity : this.list.getEntities()) {
			ComponentValue val = (ComponentValue) entity;
			val.setIs_main(value == val);
		}
		this.tableViewer.refresh();
	}

}